package com.moonspeak.boot.logwatch;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.io.file.Tailer;
import cn.hutool.core.util.StrUtil;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.websocket.OnClose;
import javax.websocket.OnError;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.ServerEndpoint;

@Slf4j
@ServerEndpoint("/log")
public class LogWebSocketHandle {

	/**
	 * 日志路径
	 */
	public static String LOG_PATH;

	public LogWebSocketHandle(){
		log.info("init logWatch!");
	}

	/**
	 * 开启websocket
	 * Description : 
	 * @param session
	 */
	@SneakyThrows
	@OnOpen
	public void onOpen(Session session){
		if(StrUtil.isBlank(LOG_PATH)){
			return;
		}
		session.getBasicRemote().sendText("=========================开启日志链接========================================");
		WebSocketLineHandler lineHandler=new WebSocketLineHandler(session);
		Tailer tailer = new Tailer(FileUtil.file(LOG_PATH), lineHandler, 2);
		tailer.start();
	}
	
	/**
	 * 关闭websocket
	 * Description :
	 */
	@OnClose
	public void onClose(){
		log.debug("=========================关闭日志链接========================================");
	}

	@OnError
	public void onError(Throwable thr){
		thr.printStackTrace();
	}






}